package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 删除搜索历史记录
     *
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
       //1.参数校验
        if (historySearchDto==null){
            return ResponseResult.okResult();
        }
        //2.用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null||user.getId()==0){
            return ResponseResult.okResult();
        }
        //3.删除
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId())),ApUserSearch.class);
        log.info("**** mongoTemplate remove success id:"+historySearchDto.getId());
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSerarch() {
        //1.用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == 0) {
            return ResponseResult.okResult();
        }
        //2.查询
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        //3.返回结果
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 保存用户历史搜索记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async //异步
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户搜索的关键词
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(userId)
                .and("keyword").is(keyword)), ApUserSearch.class);
        //2.若存在，更新创建时间
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        //3.不存在

        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        userSearch = new ApUserSearch();
        userSearch.setEntryId(userId);
        userSearch.setCreatedTime(new Date());
        userSearch.setKeyword(keyword);
        //若当前记录数量不超过10
        if (userSearchList == null || userSearchList.size() < 10) {
            mongoTemplate.save(userSearch);
            log.info("新增搜索记录成功");
        } else {//超过  替换最后一条
            ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("_id").is(lastUserSearch.getId())), userSearch);
            log.info("替换搜索记录成功");
        }

    }
}
